package com.idp.web.test.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idp.common.base.BaseController;
import com.idp.common.persistence.Page;
import com.idp.common.util.ExcelUtil;
import com.idp.common.util.FileUtils;
import com.idp.common.util.ValidateUtils;
import com.idp.web.test.entity.DetailList;
import com.idp.web.test.entity.Out;
import com.idp.web.test.entity.OutCause;
import com.idp.web.test.entity.OutStatus;
import com.idp.web.test.entity.Put;
import com.idp.web.test.entity.PutStatus;
import com.idp.web.test.entity.Warehouse;
import com.idp.web.test.service.DetailListService;
import com.idp.web.test.service.OutCauseService;
import com.idp.web.test.service.OutService;
import com.idp.web.test.service.OutStatusService;
import com.idp.web.test.service.WarehouseService;

import net.sf.json.JSONObject;

/**
 * 
 * 1111111controller
 * 
 * <pre>
 * 	历史记录：
 * 	2017-06-02 Amber
 * 	新建文件
 * </pre>
 * 
 * @author
 * 
 * 		<pre>
 * SD
 * 	Amber
 * PG
 *	Amber
 * UT
 *
 * MA
 *         </pre>
 * 
 * @version $Rev$
 *
 *          <p/>
 *          $Id$
 *
 */
@Controller
@RequestMapping("/out")
public class OutController extends BaseController {

	private Logger logger = Logger.getLogger(OutController.class);

	@Resource
	private OutService outService;

	@Resource
	private WarehouseService WarehouseService;

	@Resource
	private OutStatusService outStatusService;

	@Resource
	private DetailListService detailListService;

	@Resource
	private WarehouseService warehouseService;

	@Resource
	private OutCauseService outCauseService;

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	初始化查询页面
	 * </pre>
	 * 
	 * @return
	 */
	@RequestMapping("/init")
	public String init(HttpServletRequest request) {

		try {
			request.setAttribute("warehouses", WarehouseService.findBySearch(new Warehouse()));
			request.setAttribute("outStatus", outStatusService.findBySearch(new OutStatus()));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "shopping/out/outSearch";
	}

	/**
	 * 按条件查询
	 * 
	 * @param out
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping("/searchLists")
	public String searchList(Out out, Page<Out> page, HttpServletRequest request) {
		try {
			if (out.getWarehouseId() == 0) {
				out.setWarehouseId(null);
			}
			if (out.getOutStatusId() == 0) {
				out.setOutStatusId(null);
			}
			request.setAttribute("page", outService.sreachByWarehouseAndOutStatus(out, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/out/outList";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	新增修改页面初始化
	 * </pre>
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/out")
	public String out(Integer id, HttpServletRequest request) {
		try {
			List<Warehouse> warehouses = warehouseService.findBySearch(new Warehouse());
			List<OutCause> outCauses = outCauseService.listAll();
			if (ValidateUtils.isNotEmpty(id)) {
				Out out = outService.getById(id);
				request.setAttribute("out", out);
			}
			request.setAttribute("warehouses", warehouses);
			request.setAttribute("outCauses", outCauses);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/out/out";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	保存
	 * </pre>
	 * 
	 * @param out
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(Out out) {
		JSONObject json = new JSONObject();
		try {
			// 修改
			if (ValidateUtils.isNotEmpty(out.getId())) {
				outService.updateNotNull(out);
			}
			// 新增
			else {
				outService.add(out);
			}
			json.put("result", "save_success");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("result", "save_fail");
		}
		return json.toString();
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	删除
	 * </pre>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(Integer id) {
		JSONObject json = new JSONObject();
		Out out = new Out();
		try {
			out.setId(id);
			out.setOutStatusId(4);
			outService.updateNotNull(out);
			json.put("result", "delete_success");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "delete_fail");
		}

		return json.toString();
	}

	/**
	 * 批量出库信息
	 * 
	 * @return
	 */
	@RequestMapping("/batchMakeSure")
	@ResponseBody
	public String batchMakeSure(@RequestParam(value = "ids[]", required = false) Integer[] ids) {
		JSONObject jsonObject = new JSONObject();
		int result = outService.makeSureOut(ids);
		if (result == 1) {
			jsonObject.put("result", "success");
		} else {
			jsonObject.put("result", "faile");
		}
		return jsonObject.toString();
	}

	/**
	 * 批量导出数据
	 * 
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/batchExport")
	public String batchExport(Integer warehouseId, Integer statusId, String beginTime, String endTime,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<>();
		map.put("warehouseId", warehouseId);
		Warehouse warehouse = warehouseService.getById(warehouseId);
		OutStatus outStatus = new OutStatus();
		if (statusId != 0) {
			map.put("statusId", statusId);
			outStatus = outStatusService.getById(statusId);
		} else {
			outStatus.setName("全部");
		}
		if (!"".equals(beginTime)) {
			map.put("beginTime", beginTime);
		}
		if (!"".equals(endTime)) {
			map.put("endTime", endTime);
		}
		List<Out> outs = outService.findByMap(map);
		HSSFWorkbook workbook = ExcelUtil.createOutWorkBook(outs);
		// --------------------------- //
		String fileName = warehouse.getName() + "-" + outStatus.getName() + "-" + beginTime + "至" + endTime;
		fileName = FileUtils.encodingFileName(fileName);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			workbook.write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置reponse参数,打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			ServletOutputStream sos = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(sos);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
		return null;
	}
}
